let isDirty = false;

$('#save_success').text("");
$('#save').click(function () {
    if (!isDirty) return;
    let mapping_regexps = $("#mapping-wrapper form input").toArray().map(v => $(v).val());
    let mapping_folders = $("#mapping-wrapper form select").toArray().map(v => $(v).val());
    $("#status").removeClass("has-success");
    $("#status").removeClass("has-error");
    let mappings = [];
    try {
        mapping_regexps.forEach((regexp, i) => {
            let folder = mapping_folders[i];
            // 测试正则表达式是否合法
            new RegExp(regexp);
            mappings.push([
                regexp,
                folder,
            ]);
        });
    } catch (error) {
        $("#status").addClass("has-error");
        $('#save_success').text(`Try again after checking mapping format. ${error.message}`);
        return;
    }

    
    let mutex_regexps = $("#mutex-wrapper form input").toArray().map(v => $(v).val());
    try {
        mutex_regexps.forEach((regexp, i) => {
            let folder = mapping_folders[i];
            // 测试正则表达式是否合法
            new RegExp(regexp);
        });
    } catch (error) {
        $("#status").addClass("has-error");
        $('#save_success').text(`Try again after checking mutex format. ${error.message}`);
        return;
    }

    chrome.storage.sync.set({
        [StorageKey.BOOKMAP_MAPPINGS]: JSON.stringify(mappings),
        [StorageKey.MUTEXT_RULES]: JSON.stringify(mutex_regexps),
        [StorageKey.MUTEX_SAME_INDEX]: $("#mutex_same_index")[0].checked ? 1 : 0,
        [StorageKey.AUTO_CLOSE_POPUP]: $("#auto_close_popup")[0].checked ? 1 : 0,
    }, function () {
        $("#status").addClass("has-success");
        $('#save_success').text("Save successfully!");
        setTimeout(() => {
            $('#save_success').text("");
        }, 2000);
    });
    
    resetDirty();
});

let folderIds = [];
let folderTitles = {};
chrome.bookmarks.getTree(
    function (bookmarkTreeNodes) {
        console.log(bookmarkTreeNodes);
        folderIds = recursiveBookmarkTreeNodes(bookmarkTreeNodes);
        console.log(folderIds);
        folderIds.forEach((nodeid, i) => {
            let node;
            let titles = [];
            let tmpid = nodeid;
            while (node = id2node[tmpid]) {
                titles.unshift(node.title);
                tmpid = node.parentId;
            }
            folderTitles[nodeid] = titles;
        });

        chrome.storage.sync.get([StorageKey.BOOKMAP_MAPPINGS, StorageKey.MUTEXT_RULES, StorageKey.MUTEX_SAME_INDEX, StorageKey.AUTO_CLOSE_POPUP], function (result) {
            let mappings = JSON.parse(result[StorageKey.BOOKMAP_MAPPINGS] || DefaultBookmarkMappings);
            mappings.forEach(v => {
                createMappingRule(v[0], v[1]);
            });

            
            let mutexs = JSON.parse(result[StorageKey.MUTEXT_RULES] || DefaultMutextRules);
            mutexs.forEach(v => {
                createMutexRule(v);
            });
            $("#mutex_same_index")[0].checked = result[StorageKey.MUTEX_SAME_INDEX] == 1;
            $("#auto_close_popup")[0].checked = result[StorageKey.AUTO_CLOSE_POPUP] == 1;
        });
    }
);

$("#add-mapping-rule").click(function () {
    createMappingRule('');
    setDirty();
});

$("#add-mutex-rule").click(function () {
    createMutexRule('');
    setDirty();
});
$("#mutex_same_index").change(function() {
    setDirty();
});
$("#auto_close_popup").change(function() {
    setDirty();
});

function setDirty() {
    if (isDirty) return;
    isDirty = true;
    $("#save").toggleClass("btn-success btn-default");
}

function resetDirty() {
    if (!isDirty) return;
    isDirty = false;
    $("#save").toggleClass("btn-success btn-default");
}


function createMappingRule(url, folder) {
    $("#mapping-wrapper").append(`
    <form class="form-horizontal" >
        <button type="button" class="btn btn-danger pull-right"><img src="/assets/remove.png"></button>
        <p class="clearfix"></p>
        <div class="form-group" >
            <label class="col-sm-3 control-label">RegExp of URL</label>
            <div class="col-sm-9">
                <input class="form-control" rows="6" value="${url}" placeholder='Regular expression likes github.com'></input>
            </div>
        </div>
        <div class="form-group">
            <label class="col-sm-3 control-label">Folder</label>
            <div class="col-sm-9">
                <select class="form-select" style="width: 100%; height: 2em;">
                    ${folderIds.map(folderId => {
                        let folderPath = folderTitles[folderId].join(folder_path_separtor);
                        return `<option value="${folderPath}" ${ folderPath == folder ? "selected" : ""}>${folderPath}</option>"`
                    })}
                </select>
            </div>
        </div>
    </form>
    `);
    $("#mapping-wrapper button.btn-danger").last().click(function(event) {
        event.currentTarget.parentNode.remove();
        setDirty();
    });
    $("#mapping-wrapper input").last().change(setDirty);
    $("#mapping-wrapper select").last().change(setDirty);
}
function createMutexRule(url) {
    $("#mutex-wrapper").append(`
    <form class="form-horizontal" >
        <button type="button" class="btn btn-danger pull-right"><img src="/assets/remove.png"></button>
        <p class="clearfix"></p>
        <div class="form-group" >
            <label class="col-sm-3 control-label">RegExp of URL</label>
            <div class="col-sm-9">
                <input class="form-control" rows="6" value="${url}" placeholder='Regular expression likes www.youtube.com/watch\\?v=.*&list=foobar'></input>
            </div>
        </div>
    </form>
    `);
    $("#mutex-wrapper button.btn-danger").last().click(function(event) {
        event.currentTarget.parentNode.remove();
        setDirty();
    });
    
    $("#mutex-wrapper input").last().change(setDirty);
}

$(window).on('beforeunload', function(){
    return isDirty || undefined;
});